package cn.lg.soar.core.util.easyexcel.translate;

import cn.lg.soar.common.util.trans.handler.ITranslateHandler;
import cn.lg.soar.common.util.trans.model.TranslateContext;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.lang.NonNull;

import java.lang.annotation.Annotation;
import java.util.List;

/**
 * 内部翻译转换器
 * @author luguoxiang
 * @date 2022/8/31
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Getter
@Setter
class InnerTranslateConverter<T> implements Converter<T> {

    private TranslateContext<T> context;

    private ITranslateHandler<T> handler;

    private Annotation annotation;

    public InnerTranslateConverter(@NonNull TranslateContext<T> context, Annotation annotation) {
        this.context = context;
        this.handler = context.getHandler();
        this.annotation = annotation;
    }

    public T toJava(String value) {
        return handler.convertToJava(value, annotation, context);
    }

    public String toExcel(Object value) {
        if (value == null) {
            return null;
        }
        Object o = handler.convertByJava((T) value, annotation, context);
        if (o instanceof List) {
            return String.join(", ", ((List<String>) o));
        }
        if (o == null) {
            return value.toString();
        }
        return o.toString();
    }

    @Override
    public Class<Object> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public T convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return toJava(cellData.getStringValue());

    }

    @Override
    public WriteCellData<?> convertToExcelData(Object o, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new WriteCellData<>(toExcel(o));
    }

}
